package com.gl.saasservice.sys.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gl.common.util.DownloadUtil;
import com.gl.common.util.SecurityUtils;
import com.gl.common.util.StringUtils;
import com.gl.common.util.sql.SqlUtils;
import com.gl.common.vo.ApiData;
import com.gl.common.vo.ResultBean;
import com.gl.framework.config.sms.SmsConfig;
import com.gl.framework.web.response.Result;
import com.gl.framework.web.response.ResultCode;
import com.gl.portal.system.vo.SysUserVo;
import com.gl.saasservice.entity.*;
import com.gl.saasservice.house.entity.BacklogItem;
import com.gl.saasservice.house.repository.BacklogItemRepository;
import com.gl.saasservice.house.repository.CommunityRepository;
import com.gl.saasservice.house.repository.HouseRepository;
import com.gl.saasservice.repository.*;
import com.gl.saasservice.smartlock.haixiaoke.SmartLockHxkService;
import com.gl.saasservice.sms.service.SmsService;
import com.gl.saasservice.sys.vo.*;
import com.google.common.collect.Maps;
import com.haixiaoke.saas.repository.util.GsonUtil;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * CPU卡库管理
 */
@Slf4j
@Service
public class CardWarehouseService {
    private static final Logger LOG = LoggerFactory.getLogger(CardWarehouseService.class);

    private static final String LOCK_ORDER = " ORDER BY l.operator_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MCardRecordRepository mCardRecordRepository;//CPU操作记录
    @Autowired
    private MCardWarehouseRepository mCardWarehouseRepository;//CPU卡库管理
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;//卡授权-授权类型明细表
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;//智能锁用户授权明细表
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private SmsService smsService;//模板短信处理
    @Autowired
    private BacklogItemRepository backlogItemRepository;//待办事项
    @Autowired
    private BacklogItemCardRefRepository backlogItemCardRefRepository;//
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private SmartLockUserRepository smartLockUserRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Value("${app.authCards_url}")
    private String authCardsUrl;
    @Value("${app.frozenOrUnfrozenChamada_url}")
    private String frozenOrUnfrozenChamadaUrl;
    @Value("${app.delCardAuth_url}")
    private String delCardAuthUrl;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${tianWangHulian_url}")
    private String tianWangHuLianCallbackUrl;
    @Value("${tianwanghulian_appKey}")
    private String tianWangHuLianAppKey;
    @Value("${tianwanghulian_secret}")
    private String tianWangHuLianSecret;
    @Autowired
    private SmartLockHxkService smartLockHxkService;

    /**
     *列表
     * @param accessToken
     * @param vo
     * @return
     */
    public Result list(String accessToken,  CardWarehouseVo vo) {
        LOG.info("---RoleService delete accessToken={},vo={}", accessToken, vo);

        String SQL = " select a.*,b.user_name as recordUserName, c.user_name as operatorName from  m_card_warehouse a \n" +
                "                LEFT JOIN sys_user  b on b.id=a.record_user_id\n" +
                "LEFT JOIN sys_user  c on c.id=a.operator_id ";

        String count = " select count(1)  from  m_card_warehouse a \n" +
                "                LEFT JOIN sys_user  b on b.id=a.record_user_id\n" +
                "LEFT JOIN sys_user  c on c.id=a.operator_id  ";

        String offsets = "   limit ? offset ?";

        StringBuilder where = new StringBuilder("WHERE 1 = 1 \n");


        //卡号
        if (StringUtils.isNotEmpty(vo.getCardNumber())){
            where.append(" and  a.card_number like '%"+vo.getCardNumber()+"%'");
        }

        //卡id
        if (StringUtils.isNotEmpty(vo.getCardId())){
            where.append(" and a.card_id like '%"+vo.getCardId()+"%'");
        }


        //使用状态 是否已使用 0否 1是
        if (vo.getUseStatus() !=null ){
            where.append(" and a.use_status = "+ vo.getUseStatus());
        }

        //冻结状态 0无 1正常 2已冻结
        if (vo.getFreezeThawStatus() !=null ){
            where.append(" and a.freeze_thaw_status = "+ vo.getFreezeThawStatus());
        }

        //录入人iD  创建人
        if (StringUtils.isNotEmpty(vo.getRecordUserId() ) ){
            where.append(" and  a.record_user_id = "+ vo.getRecordUserId());
        }

        //操作人
        if (StringUtils.isNotEmpty(vo.getOperatorName() ) ){
            where.append(" and a.operator_id in( select id  from sys_user  where user_name  like '%"+vo.getOperatorName()+"%' )"  );
        }


        ApiData<CardVo> apiData = new ApiData<>();

        Long total = jdbcTemplate.queryForObject(count + where, Long.class);
        if (total == 0) {
            return Result.success(apiData);
        }
        if (StringUtils.isBlank(vo.getRecordTimes())){
            vo.setRecordTimes("desc");
        }
        // 查询分页数据
        where.append(" ORDER BY ").append(" a.record_time  "+vo.getRecordTimes() ).append(" \n").append(offsets);
        List<Object> args = new ArrayList<>();
        args.add(vo.getPageSize());
        args.add(vo.getPageNumber() * vo.getPageSize());
        List<CardVo> data = jdbcTemplate.query(SQL + where, new BeanPropertyRowMapper<>(CardVo.class), args.toArray());

        apiData.setTotal(total);
        apiData.setData(data);

        return Result.success(apiData);

    }

    /**
     *冻结内容
     * @param accessToken
     * @param vo
     * @return
     */
    public Result freezeContent(String accessToken,  CardWarehouseVo vo) {
        LOG.info("---RoleService delete accessToken={},vo={}", accessToken, vo);

        String SQL = "select \n" +
                "b.remark,\n" +
                "b.operator_id as operatorId,\n" +
                "c.user_name as operatorName,\n" +
                "b.operator_time as operatorTime\n" +
                "from  m_card_warehouse a  \n" +
                "LEFT JOIN m_card_record b on b.card_warehouse_id =a.id\n" +
                "LEFT JOIN sys_user c on c.id=b.operator_id\n" +
                "where  b.type =  "+vo.getType()+" and  a.id="+vo.getId()+" GROUP BY b.operator_time desc LIMIT 1  ";


        List<CardVo> data = jdbcTemplate.query(SQL , new BeanPropertyRowMapper<>(CardVo.class));
        if (null == data || data.size()<=0){
            return Result.success(null);
        }
        return Result.success(data.get(0));
    }


    /**
     *详情
     * @param accessToken
     * @param vo
     * @return
     */
    public Result info(String accessToken,  CardWarehouseVo vo) {
        LOG.info("---RoleService delete accessToken={},vo={}", accessToken, vo);
        Optional<MCardWarehouse> mCardWarehouse = mCardWarehouseRepository.findById(vo.getId());

        if (!mCardWarehouse.isPresent()){
            return Result.fail("数据不存在！");
        }
        MCardWarehouse card = mCardWarehouse.get();

        ApiData<CardInfoVo> apiData = new ApiData<>();

        String sql ="select b.user_name as userName,\n" +
                " b.mobile  as userMoblie,\n" +
                " d1.NAME as provinceName,  \n" +
                " d2.NAME as cityName,  \n" +
                " d3.NAME as districtName,  \n" +
                " d4.NAME as streetName,  \n" +
                " e.name as communityName,  \n" +
                " f.name as buildName, \n" +
                " g.name as unitName, \n" +
                " a.id as lockCardId, \n" +
                " c.room_number as roomNumber \n" +
                "from  saas_smart_lock_card a  \n" +
                "LEFT JOIN saas_smart_lock_auth b on a.lock_auth_id=b.id\n" +
                "LEFT JOIN saas_house c on c.id=b.house_id\n" +
                "LEFT JOIN sys_area d1  on d1.id=c.province_id\n" +
                "LEFT JOIN sys_area d2  on d2.id=c.city_id\n" +
                "LEFT JOIN sys_area d3  on d3.id=c.district_id\n" +
                "LEFT JOIN sys_area d4  on d4.id=c.street_id\n" +
                "LEFT JOIN saas_community e  on e.id=c.residence_community_id\n" +
                "LEFT JOIN saas_community_build f  on f.id=c.building_num\n" +
                "LEFT JOIN saas_community_build_unit g  on g.id=c.unit\n" +
                "where a.card_id= '"+ card.getCardId()+"'";

        String offsets = "   limit ? offset ?";
        StringBuilder where = new StringBuilder();
        //省id
        if (vo.getProvinceId() !=null ){
            where.append(" and c.province_id = "+vo.getProvinceId());
        }

        //市ID
        if (vo.getCityId() !=null ){
            where.append(" and c.city_id = "+vo.getCityId());
        }

        //区ID
        if (vo.getDistrictId() !=null ){
            where.append(" and c.district_id = "+vo.getDistrictId());
        }

        //街道ID
        if (vo.getStreetId() !=null ){
            where.append(" and c.street_id = "+vo.getStreetId());
        }

        //小区ID
        if (vo.getCommunityId() !=null ){
            where.append(" and c.residence_community_id = '"+vo.getCommunityId()+"'");
        }

        //楼栋ID
        if (vo.getBuildingNum() !=null ){
            where.append(" and c.building_num = "+vo.getBuildingNum());
        }

        //单元ID
        if (vo.getUnitId() !=null ){
            where.append(" and c.unit = "+vo.getUnitId());
        }

        //房号
        if (StringUtils.isNotBlank(vo.getRoomNumber()) ){
            where.append(" and c.room_number = "+vo.getRoomNumber());
        }


        //住户姓名
        if (StringUtils.isNotBlank(vo.getUserName()) ){
            where.append(" and b.user_name like '%"+vo.getUserName()+"%'");
        }

        //住户手机号
        if (StringUtils.isNotBlank(vo.getUserMoblie()) ){
            where.append(" and b.mobile like '%"+vo.getUserMoblie()+"%'");
        }

        List<CardInfoVo> query = jdbcTemplate.query(sql+where, new BeanPropertyRowMapper<>(CardInfoVo.class));
        if (null == query || query.size()<=0){

            return Result.success(apiData);
        }
        List<Object> args = new ArrayList<>();
        args.add(vo.getPageSize());
        args.add(vo.getPageNumber() * vo.getPageSize());
        where.append(offsets);
        List<CardInfoVo> list = jdbcTemplate.query(sql+where, new BeanPropertyRowMapper<>(CardInfoVo.class), args.toArray());
        apiData.setTotal((long) query.size());
        apiData.setData(list);
        return Result.success(apiData);
    }


    /**
     * 添加卡
     * @param accessToken
     * @param vo
     * @return
     */
    public Result save(String accessToken, CardWarehouseVo vo) {
        LOG.info("---RoleService save accessToken={},vo={}", accessToken, JSON.toJSONString(vo));
        SysUserVo user = SecurityUtils.getLoginUser().getUser();


        if (vo.getCardId().equals(vo.getCardNumber())){
            return Result.fail("卡号和卡ID不能一样！");
        }
        List<MCardWarehouse> cardId = mCardWarehouseRepository.findByCardId(vo.getCardId());
        if (cardId !=null && cardId.size()>0){
            return Result.fail("卡ID已存在，请重新输入！");
        }
        List<MCardWarehouse> cardNumber = mCardWarehouseRepository.findByCardNumber(vo.getCardNumber());
        if (cardNumber !=null && cardNumber.size()>0){
            return Result.fail("卡号已存在，请重新输入！");
        }
        MCardWarehouse entity = new MCardWarehouse();
        entity.setCardNumber(vo.getCardNumber());//卡号
        entity.setCardId(vo.getCardId());//卡id
        entity.setRecordUserId(String.valueOf(user.getId()));//录入人iD
        entity.setRecordTime(new Date());//录入时间
        entity.setUseStatus((byte) 0);//是否已使用 0否 1是
        entity.setFreezeThawStatus((byte) 0);//0无 1正常 2已冻结
        entity.setOperatorId(String.valueOf(user.getId()));//操作人
        entity.setOperatorTime(new Date());//操作时间
        mCardWarehouseRepository.save(entity);

        return Result.success(null);
    }

    /**
     * 修改卡
     * @param accessToken
     * @param vo
     * @return
     */
    public Result update(String accessToken, CardWarehouseVo vo) {
        LOG.info("---RoleService save accessToken={},vo={}", accessToken, JSON.toJSONString(vo));
        SysUserVo user = SecurityUtils.getLoginUser().getUser();
        Optional<MCardWarehouse> mCardWarehouse = mCardWarehouseRepository.findById(vo.getId());

        if (!mCardWarehouse.isPresent()){
            return Result.fail("数据不存在！");
        }
        MCardWarehouse entity = mCardWarehouse.get();

        if (vo.getCardId().equals(vo.getCardNumber())){
            return Result.fail("卡号和卡ID不能一样！");
        }
        List<MCardWarehouse> cardId = mCardWarehouseRepository.findByCardId(vo.getCardId());
        if (!cardId.isEmpty()) {
            for (MCardWarehouse card : cardId) {
                if (card.getId() != vo.getId()) {
                    return Result.fail("卡ID已存在，请重新输入！");
                }

            }
        }

        List<MCardWarehouse> cardNumber = mCardWarehouseRepository.findByCardNumber(vo.getCardNumber());
        if (!cardNumber.isEmpty()) {
            for (MCardWarehouse card : cardNumber) {
                if (card.getId() != vo.getId()) {
                    return Result.fail("卡号已存在，请重新输入！");
                }
            }
        }

        entity.setCardNumber(vo.getCardNumber());//卡号
        entity.setOperatorId(String.valueOf(user.getId()));//操作人
        entity.setOperatorTime(new Date());//操作时间
        mCardWarehouseRepository.save(entity);

        return Result.success(null);
    }

    /**
     *删除卡
     * @param accessToken
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result delete(String accessToken,  List<Long> ids) {
        LOG.info("---RoleService delete accessToken={},ids={}", accessToken, ids);

        for (Long id : ids) {
            Optional<MCardWarehouse> mCardWarehouse = mCardWarehouseRepository.findById(id);
            if (!mCardWarehouse.isPresent()){
                return Result.fail("ID为 "+id +" 数据不存在！");
            }
            MCardWarehouse entity = mCardWarehouse.get();
            if (entity.getUseStatus()==1){
                return Result.fail("ID为 "+id +" 已使用不可删除！");
            }
            mCardWarehouseRepository.deleteById(entity.getId());
        }
        return Result.success(null);
    }


    /**
     *解绑卡
     * @param accessToken
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result unbind(String accessToken,  Long id) {
        LOG.info("---RoleService delete accessToken={},id={}", accessToken, id);
        /**
         * 解绑：删除智能锁中，该卡授权记录，同时清理卡与用户的关系数据。向用户推送解绑信息，以短信的形式推送。
         * 补充说明：解绑后，冻结/解冻状态修改为：0(无)，修改使用状态为：0
         */
        SysUserVo user = SecurityUtils.getLoginUser().getUser();
        Optional<MCardWarehouse> cardWarehouse = mCardWarehouseRepository.findById(id);
        if (!cardWarehouse.isPresent()){
            return Result.fail("数据不存在！");
        }
        MCardWarehouse entity = cardWarehouse.get();

        //根据卡ID获得卡数据
        List<SmartLockCard> lockCard = smartLockCardRepository.findByCardId(entity.getCardId());
        if (null != lockCard && lockCard.size()>0){

            //拿到用户授权ID，
            List<Long> lockAuthId = lockCard.stream().map(x -> x.getLockAuthId()).collect(Collectors.toList());
            for (SmartLockCard smartLockCard : lockCard) {
                log.info("用户授权id:"+smartLockCard.getLockAuthId());
                //新增判断是否是四代智能锁
                Long lockId = smartLockCard.getLockId();
                Optional<SmartLock> byId = smartLockRepository.findById(lockId);
                Long brandId = byId.get().getBrandId();
                if (brandId == 4) {
                    String sn = byId.get().getSn();
                    String identification = smartLockCard.getIdentification();
                    String resultStr = deleteCard(identification,sn);
                    cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
                    Integer code = (Integer) jsonObject.get("code");
                    String msg = (String) jsonObject.get("msg");
                    if (code != 0) {
                        return  Result.fail(msg);
                    }
                } else {
                    String responseMsg = delCardAuthUrlHttpGet(smartLockCard.getLockAuthId());
                    if (responseMsg.equals("2")){
                        return Result.fail("解绑异常，请与管理员联系！");
                    }else if (!responseMsg.equals("2") && !responseMsg.equals("1")){
                        return Result.fail(responseMsg);
                    }
                }
            }

            //更具卡ID 删除卡数据
            smartLockCardRepository.deleteByCardId(entity.getCardId());

            List<SmartLockAuth> smartLockAuthList = smartLockAuthRepository.findByIdIn(lockAuthId);
            for (SmartLockAuth smartLockAuth : smartLockAuthList) {
                //调用短信接口发送短信
               smsService.sendTemplateSms(smartLockAuth.getMobile(), smsConfig.getUnbindTemplateCode());
                smartLockAuth.setCpuStatus(0);
            }
            smartLockAuthRepository.saveAll(smartLockAuthList);

        }
        //卡类型变更为未使用
        entity.setUseStatus((byte)0);// 是否已使用 0否 1是
        entity.setFreezeThawStatus((byte)0);//0无 1正常 2已冻结
        entity.setOperatorId(String.valueOf(user.getId()));//操作人
        entity.setOperatorTime(new Date());//操作时间
        mCardWarehouseRepository.save(entity);
        //添加CPU操作记录
        MCardRecord cardRecord = new MCardRecord();
        cardRecord.setCardWarehouseId(entity.getId());//CPU卡表id
        cardRecord.setType((byte)1);//1解绑、2冻结、3解冻
        cardRecord.setOperatorId(String.valueOf(user.getId()));//操作人
        cardRecord.setOperatorTime(new Date());//最后更新时间
        mCardRecordRepository.save(cardRecord);
        return Result.success(null);
    }



    /**
     *冻结卡
     * @param accessToken
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result frozen(String accessToken, CardWarehouseVo vo) {
        LOG.info("---RoleService delete accessToken={},vo={}", accessToken, vo);
        /**
         * 已使用、未冻结的卡，显示此按钮，操作冻结时，冻结该卡对应的用户授权数据(冻结人)   说明：冻结后修改冻结/解冻状态为：2
         *   补充： 冻结需要发送短信， 解绑不需要。 冻结解
         */
        SysUserVo user = SecurityUtils.getLoginUser().getUser();
        Optional<MCardWarehouse> cardWarehouse = mCardWarehouseRepository.findById(vo.getId());
        if (!cardWarehouse.isPresent()){
            return Result.fail("卡数据不存在！");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select a.id ,  \n" +
                "a.org_id as orgId,\n" +
                "b.name AS communityName,\n" +
                "c.name AS buildName,\n" +
                "d.name AS unitName ,\n" +
                "a.room_number AS roomNumber \n" +
                "from  saas_house  a\n" +
                "JOIN saas_community b ON b.id = a.  residence_community_id\n" +
                "LEFT JOIN saas_community_build c ON a.building_num = c.id  \n" +
                "LEFT JOIN saas_community_build_unit d ON a.unit = d.id  \n" +
                "where 1=1");

        MCardWarehouse entity = cardWarehouse.get();

        //根据卡ID获得卡数据
        List<SmartLockCard> lockCard = smartLockCardRepository.findByCardId(entity.getCardId());
        if (null != lockCard && lockCard.size()>0){
            //拿到用户授权ID，
            List<Long> lockAuthId = lockCard.stream().map(x -> x.getLockAuthId()).collect(Collectors.toList());

            Map<Long, SmartLockCard> lockCardMap = lockCard.stream().collect(Collectors.toMap(SmartLockCard::getLockAuthId, a -> a,(k1,k2)->k1));

            List<SmartLockAuth> smartLockAuthList = smartLockAuthRepository.findByIdIn(lockAuthId);
            List<String> houseIdList = smartLockAuthList.stream().map(x -> x.getHouseId()).collect(Collectors.toList());
            String houseId=null;
            for (int i = 0; i < houseIdList.size(); i++) {
                if (i==0){
                    houseId= "'"+houseIdList.get(0)+"'";
                }else {
                    houseId= houseId + "'"+houseIdList.get(i)+"'";
                }
            }

            List<HouseVO> houseList = jdbcTemplate.query(sql.toString() + " and a.id in( " + houseId + ") ", new BeanPropertyRowMapper<>(HouseVO.class));

            Map<String, HouseVO> houseMap = houseList.stream().collect(Collectors.toMap(HouseVO::getId, a -> a,(k1,k2)->k1));
            for (SmartLockAuth smartLockAuth : smartLockAuthList) {
                SmartLockCard smartLockCard = lockCardMap.get(smartLockAuth.getId());
                //新增判断是否是四代智能锁
                Long lockId = smartLockAuth.getLockId();
                Optional<SmartLock> byId = smartLockRepository.findById(lockId);
                Long brandId = byId.get().getBrandId();
                if (brandId == 4) {
                    String identification = smartLockCard.getIdentification();
                    String sn = byId.get().getSn();
                    String resultStr = deleteCard(identification,sn);
                    cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
                    Integer code = (Integer) jsonObject.get("code");
                    String msg = (String) jsonObject.get("msg");
                    if (code != 0) {
                        return  Result.fail(msg);
                    }
                    //调用短信接口发送短信
                    smsService.sendTemplateSmsWithData(smartLockAuth.getMobile(), smsConfig.getFrozenTemplateCode(),new String[]{vo.getRemark()});
                    smartLockAuth.setCpuStatus(2);//CPU:0未授权 1已授权 2已冻结

                    //生成代办事项
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(smartLockAuth.getHouseId());//公租房id
                    HouseVO house = houseMap.get(smartLockAuth.getHouseId());
                    if (null != house){
                        backlogItem.setOrgId(house.getOrgId());//产权单位id
                        if (StringUtils.isNotEmpty(house.getCommunityName())){
                            backlogItem.setContent(house.getCommunityName()+"-"+house.getBuildName()
                                    +"-"+house.getUnitName()+"-"+house.getRoomNumber()+"已冻结");//内容   房屋小区-楼栋-单元-房号+已冻结
                        }
                    }

                    backlogItem.setType(34);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
                    // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结
                    backlogItem.setTitle("cpu卡冻结");//标题
                    backlogItem.setHandleStatus(0);//事项处理状态：0未读/未处理  1已读/已处理
                    backlogItem.setMatchUserId(smartLockAuth.getAuthorUserId());//承租人id/被冻结人
                    backlogItem.setOperatorId(String.valueOf(user.getId()));//操作人id
                    backlogItem.setCreateTime(new Date());//创建时间
                    backlogItem.setPhone(smartLockAuth.getMobile());//手机号
                    BacklogItem save = backlogItemRepository.save(backlogItem);

                    BacklogItemCard backlogItemCard = new BacklogItemCard();
                    backlogItemCard.setBacklogItemId(save.getId());//待办事项id
                    backlogItemCard.setType((byte)1);//1冻结、2解冻
                    backlogItemCard.setRemark(vo.getRemark());//冻结原因
                    backlogItemCard.setOperatorTime(new Date());//操作时间
                    backlogItemCardRefRepository.save(backlogItemCard);
                } else {
                    String responseMsg = frozenOrUnfrozenChamadaUrlHttpGet(smartLockCard.getLockId(),smartLockCard.getLockAuthId(),1,vo.getRemark());
                    if (responseMsg.equals("2")){
                        return Result.fail("冻结异常，请与管理员联系！");
                    }else if (!responseMsg.equals("2") && !responseMsg.equals("1")){
                        return Result.fail(responseMsg);
                    }

                    //调用短信接口发送短信
                    smsService.sendTemplateSmsWithData(smartLockAuth.getMobile(), smsConfig.getFrozenTemplateCode(),new String[]{vo.getRemark()});
                    smartLockAuth.setCpuStatus(2);//CPU:0未授权 1已授权 2已冻结

                    //生成代办事项
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(smartLockAuth.getHouseId());//公租房id
                    HouseVO house = houseMap.get(smartLockAuth.getHouseId());
                    if (null != house){
                        backlogItem.setOrgId(house.getOrgId());//产权单位id
                        if (StringUtils.isNotEmpty(house.getCommunityName())){
                            backlogItem.setContent(house.getCommunityName()+"-"+house.getBuildName()
                                    +"-"+house.getUnitName()+"-"+house.getRoomNumber()+"已冻结");//内容   房屋小区-楼栋-单元-房号+已冻结
                        }
                    }

                    backlogItem.setType(34);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
                    // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结
                    backlogItem.setTitle("cpu卡冻结");//标题
                    backlogItem.setHandleStatus(0);//事项处理状态：0未读/未处理  1已读/已处理
                    backlogItem.setMatchUserId(smartLockAuth.getAuthorUserId());//承租人id/被冻结人
                    backlogItem.setOperatorId(String.valueOf(user.getId()));//操作人id
                    backlogItem.setCreateTime(new Date());//创建时间
                    backlogItem.setPhone(smartLockAuth.getMobile());//手机号
                    BacklogItem save = backlogItemRepository.save(backlogItem);

                    BacklogItemCard backlogItemCard = new BacklogItemCard();
                    backlogItemCard.setBacklogItemId(save.getId());//待办事项id
                    backlogItemCard.setType((byte)1);//1冻结、2解冻
                    backlogItemCard.setRemark(vo.getRemark());//冻结原因
                    backlogItemCard.setOperatorTime(new Date());//操作时间
                    backlogItemCardRefRepository.save(backlogItemCard);
                }

            }
            smartLockAuthRepository.saveAll(smartLockAuthList);
        }
        //卡类型变更为未使用
        entity.setFreezeThawStatus((byte)2);//0无 1正常 2已冻结

        mCardWarehouseRepository.save(entity);
        //添加CPU操作记录
        MCardRecord cardRecord = new MCardRecord();
        cardRecord.setCardWarehouseId(entity.getId());//CPU卡表id
        cardRecord.setType((byte)2);//1解绑、2冻结、3解冻
        cardRecord.setRemark(vo.getRemark());//原因
        cardRecord.setOperatorId(String.valueOf(user.getId()));//操作人
        cardRecord.setOperatorTime(new Date());//最后更新时间
        mCardRecordRepository.save(cardRecord);
        return Result.success(null);
    }




    /**
     *解冻卡
     * @param accessToken
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result thaw(String accessToken, CardWarehouseVo vo) {
        LOG.info("---RoleService delete accessToken={},vo={}", accessToken, vo);
        /**
         * 已使用、未冻结的卡，显示此按钮，操作冻结时，冻结该卡对应的用户授权数据(冻结人)   说明：冻结后修改冻结/解冻状态为：2
         *   补充： 冻结需要发送短信， 解绑不需要。 冻结解
         */
        SysUserVo user = SecurityUtils.getLoginUser().getUser();
        Optional<MCardWarehouse> cardWarehouse = mCardWarehouseRepository.findById(vo.getId());
        if (!cardWarehouse.isPresent()){
            return Result.fail("卡数据不存在！");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select a.id ,  \n" +
                "a.org_id as orgId,\n" +
                "b.name AS communityName,\n" +
                "c.name AS buildName,\n" +
                "d.name AS unitName ,\n" +
                "a.room_number AS roomNumber \n" +
                "from  saas_house  a\n" +
                "JOIN saas_community b ON b.id = a.  residence_community_id\n" +
                "LEFT JOIN saas_community_build c ON a.building_num = c.id  \n" +
                "LEFT JOIN saas_community_build_unit d ON a.unit = d.id  \n" +
                "where 1=1");

        MCardWarehouse entity = cardWarehouse.get();

        //根据卡ID获得卡数据
        List<SmartLockCard> lockCard = smartLockCardRepository.findByCardId(entity.getCardId());
        if (null != lockCard && lockCard.size()>0){
            //拿到用户授权ID，
            List<Long> lockAuthId = lockCard.stream().map(x -> x.getLockAuthId()).collect(Collectors.toList());

            Map<Long, SmartLockCard> lockCardMap = lockCard.stream().collect(Collectors.toMap(SmartLockCard::getLockAuthId, a -> a,(k1,k2)->k1));
            List<SmartLockAuth> smartLockAuthList = smartLockAuthRepository.findByIdIn(lockAuthId);
            List<String> houseIdList = smartLockAuthList.stream().map(x -> x.getHouseId()).collect(Collectors.toList());
            String houseId=null;
            for (int i = 0; i < houseIdList.size(); i++) {
                if (i==0){
                    houseId= "'"+houseIdList.get(0)+"'";
                }else {
                    houseId= houseId + "'"+houseIdList.get(i)+"'";
                }
            }
            List<HouseVO> houseList = jdbcTemplate.query(sql.toString() + " and a.id in( " + houseId + ") ", new BeanPropertyRowMapper<>(HouseVO.class));


            Map<String, HouseVO> houseMap = houseList.stream().collect(Collectors.toMap(HouseVO::getId, a -> a,(k1,k2)->k1));
            for (SmartLockAuth smartLockAuth : smartLockAuthList) {
                SmartLockCard smartLockCard = lockCardMap.get(smartLockAuth.getId());
                //新增判断是否是四代智能锁
                Long lockId = smartLockAuth.getLockId();
                Optional<SmartLock> byId = smartLockRepository.findById(lockId);
                Long brandId = byId.get().getBrandId();
                if (brandId == 4) {
                    String sn = byId.get().getSn();
                    String resultStr = operationCardPassword(smartLockCard,sn);
                    cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
                    Integer code = (Integer) jsonObject.get("code");
                    String msg = (String) jsonObject.get("msg");
                    if (code != 0) {
                        return  Result.fail(msg);
                    }
                    smartLockAuth.setCpuStatus(1);//CPU:0未授权 1已授权 2已冻结

                    //生成代办事项
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(smartLockAuth.getHouseId());//公租房id
                    HouseVO house = houseMap.get(smartLockAuth.getHouseId());
                    if (null != house){
                        backlogItem.setOrgId(house.getOrgId());//产权单位id
                        if (StringUtils.isNotEmpty(house.getCommunityName())){
                            backlogItem.setContent(house.getCommunityName()+"-"+house.getBuildName()
                                    +"-"+house.getUnitName()+"-"+house.getRoomNumber()+"已解冻");//内容   房屋小区-楼栋-单元-房号+已解冻
                        }
                    }
                    backlogItem.setMatchUserId(smartLockAuth.getAuthorUserId());//承租人id
                    backlogItem.setType(35);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
                    // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结 35 cup卡解冻
                    backlogItem.setTitle("cpu卡解冻");//标题
                    backlogItem.setHandleStatus(0);//事项处理状态：0未读/未处理  1已读/已处理
                    backlogItem.setOperatorId(String.valueOf(user.getId()));//操作人id
                    backlogItem.setCreateTime(new Date());//创建时间
                    backlogItem.setPhone(smartLockAuth.getMobile());//手机号
                    BacklogItem save = backlogItemRepository.save(backlogItem);

                    BacklogItemCard backlogItemCard = new BacklogItemCard();
                    backlogItemCard.setBacklogItemId(save.getId());//待办事项id
                    backlogItemCard.setType((byte)2);//1冻结、2解冻
                    backlogItemCard.setRemark(vo.getRemark());//原因
                    backlogItemCard.setOperatorTime(new Date());//操作时间
                    backlogItemCardRefRepository.save(backlogItemCard);
                } else {
                    String responseMsg = frozenOrUnfrozenChamadaUrlHttpGet(smartLockCard.getLockId(),smartLockCard.getLockAuthId(),0,vo.getRemark());
                    if (responseMsg.equals("2")){
                        return Result.fail("冻结异常，请与管理员联系！");
                    }else if (!responseMsg.equals("2") && !responseMsg.equals("1")){
                        return Result.fail(responseMsg);
                    }

                    smartLockAuth.setCpuStatus(1);//CPU:0未授权 1已授权 2已冻结

                    //生成代办事项
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(smartLockAuth.getHouseId());//公租房id
                    HouseVO house = houseMap.get(smartLockAuth.getHouseId());
                    if (null != house){
                        backlogItem.setOrgId(house.getOrgId());//产权单位id
                        if (StringUtils.isNotEmpty(house.getCommunityName())){
                            backlogItem.setContent(house.getCommunityName()+"-"+house.getBuildName()
                                    +"-"+house.getUnitName()+"-"+house.getRoomNumber()+"已解冻");//内容   房屋小区-楼栋-单元-房号+已解冻
                        }
                    }
                    backlogItem.setMatchUserId(smartLockAuth.getAuthorUserId());//承租人id
                    backlogItem.setType(35);// 类型：1公租房录入 2智能锁(租金/押金) 3其它费用账单 4资格申请-配租 5备案 6合同到期 13智能锁个人绑定确认 14门锁低电量告警 15门锁离线
                    // 16资格审批 17轮候配租 18(合同)租金押金 19生成合同 20合同待确认  30 新增成员 31删除成员 32智能锁冻结  33智能锁解冻', 34 cpu卡冻结 35 cup卡解冻
                    backlogItem.setTitle("cpu卡解冻");//标题
                    backlogItem.setHandleStatus(0);//事项处理状态：0未读/未处理  1已读/已处理
                    backlogItem.setOperatorId(String.valueOf(user.getId()));//操作人id
                    backlogItem.setCreateTime(new Date());//创建时间
                    backlogItem.setPhone(smartLockAuth.getMobile());//手机号
                    BacklogItem save = backlogItemRepository.save(backlogItem);

                    BacklogItemCard backlogItemCard = new BacklogItemCard();
                    backlogItemCard.setBacklogItemId(save.getId());//待办事项id
                    backlogItemCard.setType((byte)2);//1冻结、2解冻
                    backlogItemCard.setRemark(vo.getRemark());//原因
                    backlogItemCard.setOperatorTime(new Date());//操作时间
                    backlogItemCardRefRepository.save(backlogItemCard);
                }

            }
            smartLockAuthRepository.saveAll(smartLockAuthList);
        }
        //卡类型变更为未使用
        entity.setFreezeThawStatus((byte)1);//0无 1正常 2已冻结
        mCardWarehouseRepository.save(entity);
        //添加CPU操作记录
        MCardRecord cardRecord = new MCardRecord();
        cardRecord.setCardWarehouseId(entity.getId());//CPU卡表id
        cardRecord.setType((byte)3);//1解绑、2冻结、3解冻
        cardRecord.setRemark(vo.getRemark());//原因
        cardRecord.setOperatorId(String.valueOf(user.getId()));//操作人
        cardRecord.setOperatorTime(new Date());//最后更新时间
        mCardRecordRepository.save(cardRecord);



        return Result.success(null);
    }

    /**
     * 模板下载
     */
    public void downloadFile() {
        try {
            // 读到流中
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("static/CPU卡库模板.xlsx");

            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getResponse();
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 导出文件下载

           DownloadUtil downloadUtil = new DownloadUtil();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len;
            try {
                while ((len = in.read(b)) > 0) {
                    bos.write(b, 0, len);
                }

                in.close();
            } catch (IOException e) {
                log.error("Download the document is failed,message:{}", e.getMessage());
            }

            downloadUtil.download(bos, response, "template.xlsx");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 文本文件上传
     */
    @Transactional(rollbackFor = Exception.class)
    public void exportLog(MultipartFile file ) throws Exception {

        File copyFile = null;
        try {
            if (file != null) {
                copyFile = multipartFileToFile(file);
            }
        } catch (Exception e) {
            log.error("文件上传异常", e);
        }
        InputStream is = null;
        try {
            is = new FileInputStream(copyFile);
            String fileName = copyFile.getName();
            Workbook workbook = null;
            if (fileName.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(is);//Excel 2007
            } else if (fileName.endsWith("xls")) {
                workbook = new HSSFWorkbook(is);//Excel 2003
            }

            Sheet sheet = workbook.getSheetAt(0);

            CellStyle style = workbook.createCellStyle(); // 样式对象
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setAlignment(HorizontalAlignment.CENTER);

            SysUserVo user = SecurityUtils.getLoginUser().getUser();
            Date date = new Date();

            //获得卡数据
            List<MCardWarehouse> cardAll = mCardWarehouseRepository.findAll();
            Map<String, MCardWarehouse> cardIdMap = cardAll.stream().collect(Collectors.toMap(MCardWarehouse::getCardId, a -> a,(k1,k2)->k1));
            Map<String, MCardWarehouse> cardNumber = cardAll.stream().collect(Collectors.toMap(MCardWarehouse::getCardNumber, a -> a,(k1,k2)->k1));

            ArrayList<MCardWarehouse> list = new ArrayList<>();

            Map<String, Integer> existMap = new HashMap<>();//验证同excel里记录重复
            Map<String, Integer> exist2Map = new HashMap<>();//验证同excel里记录重复
            int num = 0;//成功记录数
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);

                MCardWarehouse entity = new MCardWarehouse();
                try {
                    entity = convert2(row, sheet, style, existMap, workbook,rowNum, cardIdMap, cardNumber,exist2Map);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                if (entity.getCardId() != null) {
                    Cell cell = row.getCell(3);
                    log.info("cell={}",cell);
                    if (cell == null) {
                        cell = row.createCell(3);
                        cell.setCellValue("成功");
                        entity.setRecordUserId(String.valueOf(user.getId()));//录入人iD
                        entity.setRecordTime(date);//录入时间
                        entity.setUseStatus((byte) 0);//是否已使用 0否 1是
                        entity.setFreezeThawStatus((byte) 0);//0无 1正常 2已冻结
                        entity.setOperatorId(String.valueOf(user.getId()));//操作人
                        entity.setOperatorTime(date);//操作时间
                        list.add(entity);
                        num++;
                    } else if (cell.getCellTypeEnum() == CellType.BLANK) {
                        cell.setCellValue("成功");
                        entity.setRecordUserId(String.valueOf(user.getId()));//录入人iD
                        entity.setRecordTime(date);//录入时间
                        entity.setUseStatus((byte) 0);//是否已使用 0否 1是
                        entity.setFreezeThawStatus((byte) 0);//0无 1正常 2已冻结
                        entity.setOperatorId(String.valueOf(user.getId()));//操作人
                        entity.setOperatorTime(date);//操作时间
                        list.add(entity);
                        num++;
                    }
                }
            }

            Cell cell = sheet.getRow(0).createCell(3);
            cell.setCellValue("正常记录数: " + num);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);

            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // 导出文件下载
            DownloadUtil downloadUtil = new DownloadUtil();
             downloadUtil.download(bos, response, URLEncoder.encode(fileName + ".xlsx", "utf-8"));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }finally {
            try {
                if (copyFile != null) {
                    copyFile.delete();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);

            }
        }
    }


    /**
     *智能锁房屋列表
     */
    public Result lockList( String search, Integer bindType, Integer type, String communityId, Long buildId,
                            Long unitId, String roomNumber,  Long provinceId, Long cityId, Long districtId,Long streetId,Integer pageNumber,  Integer pageSize) {
        ApiData<LockManagerListVO> apiData = new ApiData<>();

            if (bindType == null) {
                return Result.fail("绑定类型为空");
            }
            SysUserVo user = SecurityUtils.getLoginUser().getUser();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            if (StringUtils.isNotBlank(search)) {
                where.append(" AND (l.`community_name` LIKE ? OR l.`match_user_name` LIKE ? OR l.`org_name` LIKE ? OR l.`name` LIKE ?)");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
            }

            if (type != null) {
                where.append(" AND l.`type` = ?");
                args.add(type);
            }

            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND l.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND l.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND l.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND l.`room_number` = ?");
                args.add(roomNumber);
            }

            //省
            if (null != provinceId) {
                where.append(" AND h.`province_id` = ?");
                args.add(provinceId);
            }
            //市
            if (null != cityId) {
                where.append(" AND h.`city_id` = ?");
                args.add(cityId);
            }
            //区
            if (null != districtId) {
                where.append(" AND h.`district_id` = ?");
                args.add(districtId);
            }
            //街道（县）
            if (null != streetId) {
                where.append(" AND h.`street_id` = ?");
                args.add(streetId);
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id" +
                    where, args.toArray(), Long.class);
            if (total == 0) {
                return Result.success(apiData);
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);

            List<LockManagerListVO> lockList = jdbcTemplate.query("SELECT l.id as lockId ,h.id,\n" +
                    " h.province_id as provinceId, \n" +
                    " a1.`NAME` as provinceName,\n" +
                    " h.city_id as cityId,\n" +
                    " a2.`NAME` as cityName,\n" +
                    " h.district_id as districtId,\n" +
                    " a3.`NAME` as districtName,\n" +
                    " h.street_id as streetId , \n" +
                    " a4.`NAME` as streetName, \n" +
                    "h.residence_community_id as residenceCommunityId, \n" +
                    "c.name as communityName ,\n" +
                    "h.building_num as buildingNum, \n" +
                    "b.name AS buildName,  \n" +
                    "h.unit as unit,\n" +
                    "d.name as unitName,\n" +
                    "l.bind_type as bindType,\n" +
                    "h.room_number as roomNumber\n" +
                    "FROM `saas_smart_lock` l \n" +
                    "left join `saas_house` h on l.`house_id` = h.id\n" +
                    "left join sys_area a1 on a1.id = h.province_id\n" +
                    "left join sys_area a2 on a2.id = h.city_id\n" +
                    "left join sys_area a3 on a3.id = h.district_id\n" +
                    "left join sys_area a4 on a4.id = h.street_id\n" +
                    "left join saas_community c  on c.id = h.residence_community_id\n" +
                    " LEFT JOIN saas_community_build b  ON h.building_num = b.id  \n" +
                    " LEFT JOIN saas_community_build_unit d ON h.unit = d.id  " +
                    where + LOCK_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(LockManagerListVO.class), args.toArray());


            //总授权人数
            List<Long> lockIds = lockList.stream().map(LockManagerListVO::getLockId).distinct().collect(Collectors.toList());

            String sql = "";
            if (bindType == 1) {
                sql = "SELECT lock_id AS lockId,COUNT(1) AS oauthCount FROM saas_smart_lock_auth WHERE lock_id IN "
                        + SqlUtils.foreachIn(lockIds.size()) + " AND bind_type = 0 GROUP BY lock_id";
            } else if (bindType == 2) {
                sql = "SELECT lock_id AS lockId,COUNT(1) AS oauthCount FROM saas_smart_lock_user WHERE lock_id IN "
                        + SqlUtils.foreachIn(lockIds.size()) + " AND del_status = 1 GROUP BY lock_id";
            }
            List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList(sql, lockIds.toArray());

            //个人锁管理员id
            List<Map<String, Object>> mapList2 = jdbcTemplate.queryForList("SELECT lock_id AS lockId,user_id as adminUserId FROM saas_smart_lock_user WHERE lock_id IN "
                    + SqlUtils.foreachIn(lockIds.size()) + " AND del_status = 1 AND user_type = 1 GROUP BY lock_id", lockIds.toArray());

            for (LockManagerListVO vo : lockList) {
                //授权状态
                if (vo.getOauthNumber() != null && vo.getOauthNumber() > 0) {
                    vo.setOauthStatus(1);
                } else {
                    vo.setOauthStatus(0);
                }

                String operatorTime = vo.getOperatorTime();
                vo.setOperatorTime(operatorTime == null ? "" : operatorTime);

                //总授权人数
                for (Map map : mapList1) {
                    long lockId = Long.parseLong(map.get("lockId").toString());
                    int oauthCount = Integer.parseInt(map.get("oauthCount").toString());
                    if (vo.getLockId() == lockId) {
                        vo.setOauthCount(oauthCount);
                    }
                }

                //个人锁管理员id
                for (Map map : mapList2) {
                    long lockId = Long.parseLong(map.get("lockId").toString());
                    String adminUserId = map.get("adminUserId").toString();
                    if (vo.getLockId() == lockId) {
                        vo.setAdminUserId(adminUserId);
                    }
                }

            }

            apiData.setData(lockList);
            apiData.setTotal(total);

            return Result.success(apiData);

    }

    /**
     * 授权用户列表
     *
     * @param houseId
     * @return
     */
    public Result lockAuth( String houseId) {
        try {
            SysUserVo user = SecurityUtils.getLoginUser().getUser();
            String userId = String.valueOf(user.getId());

            String phone = user.getPhone();


            if (StringUtils.isBlank(houseId)) {
                return Result.fail("公租房id为空");
            }

            List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
            if (smartLocks.isEmpty()) {
                return Result.fail("智能锁不存在");
            }
            SmartLock smartLock = smartLocks.get(0);
            Integer houseType = smartLock.getHouseType();

            LockAuthData<LockAuthVO> data = new LockAuthData<>();
            data.setLockId(smartLock.getId());
            data.setMechineStatus(smartLock.getMechineStatus());
            data.setAuthStatus(0);
            data.setReason(smartLock.getReason());

            List<SmartLockAuth> authList = smartLockAuthRepository.findByHouseIdAndBindType(houseId, 0);
            List<LockAuthVO> list = new ArrayList<>();
            for (SmartLockAuth auth : authList) {
                LockAuthVO vo = new LockAuthVO();
                vo.setLockAuthId(auth.getId());
                vo.setLockId(auth.getLockId());
                if (houseType == 1) {
                    if (auth.getUserType() == 1) {
                        vo.setUserType("承租人");
                    } else {
                        vo.setUserType("同住人");
                    }
                } else {
                    if (auth.getUserType() == 1) {
                        vo.setUserType("租户");
                    } else {
                        vo.setUserType("成员");
                    }
                }
                vo.setRelationTag(auth.getRelationTag());
                vo.setUserName(auth.getUserName());
                vo.setMobile(auth.getMobile());
                vo.setPwdStatus(auth.getPwdStatus());
                vo.setFingerprintStatus(auth.getFingerprintStatus());
                vo.setCardStatus(auth.getCardStatus());
                vo.setCpuStatus(auth.getCpuStatus());
                vo.setBleStatus(auth.getBleStatus());
                if (userId.equals(auth.getAuthorUserId() == null ? "" : auth.getAuthorUserId()) || phone.equals(auth.getMobile())) {
                    vo.setFlag(1);
                } else {
                    vo.setFlag(0);
                }
                list.add(vo);
            }
            data.setData(list);

            // 授权状态，有其中一种授权就是已授权状态
            for (LockAuthVO vo : list) {
                if (vo.getPwdStatus() == 1 || vo.getFingerprintStatus() == 1 || vo.getCardStatus() == 1
                        || vo.getCpuStatus() == 1 || vo.getBleStatus() == 1) {
                    data.setAuthStatus(1);
                    break;
                }
            }

            return Result.success(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }


    /**
     * 授权卡
     */
    @Transactional
    public Result authCard(Long lockAuthId, Long lockId, Integer type,
                                       String cardNumber, String cardId, Integer authType, Integer value) {
        List<MCardWarehouse> byCardId = mCardWarehouseRepository.findByCardId(cardId);

        if (null ==byCardId || byCardId.size()<=0){
            return Result.fail("卡数据不存在！");
        }
        //新增天网互联授权CPU卡
        Optional<SmartLock> byId = smartLockRepository.findById(lockId);
        Long brandId = byId.get().getBrandId();
        if (brandId == 4 || brandId == 5) {
            Date date = new Date();
            SmartLockCard smartLockCard = smartLockCardRepository.findByLockAuthIdAndType(lockAuthId, type);
            if (smartLockCard == null) {// 新增
                smartLockCard = new SmartLockCard();
                smartLockCard.setLockId(lockId);
                smartLockCard.setLockAuthId(lockAuthId);
                smartLockCard.setType(type);
                smartLockCard.setCreateTime(new Date());

                // 卡序号:50-100
                List<SmartLockCard> smartLockCards = smartLockCardRepository.findByLockId(lockId);
                if (smartLockCards != null && !smartLockCards.isEmpty()) {// 已存在序号
                    List<Integer> indexs = smartLockCards.stream().filter(vo -> vo.getCardIndex() != null)
                            .map(SmartLockCard::getCardIndex).distinct().collect(Collectors.toList());
                    Integer max = Collections.max(indexs);
                    if (max == 100) {
                        // 排除已有序号，取50-100间的最小值
                        List<Integer> list = new ArrayList<>();
                        for (int i = 49, j = 100; i < j; ++i) {
                            list.add(i + 1);
                        }
                        for (Integer i : indexs) {
                            list.remove(i);
                        }
                        Integer min = Collections.min(list);
                        smartLockCard.setCardIndex(min);
                    } else {
                        smartLockCard.setCardIndex(max + 1);// 取智能锁密码序号最大值 +1
                    }
                } else {// 没有序号
                    smartLockCard.setCardIndex(50);
                }
            }
            smartLockCard.setAuthType(authType);
            smartLockCard.setAuthTime(date);
            smartLockCard.setCardNumber(cardNumber);
            smartLockCard.setCardId(cardId);
            smartLockCard.setStatus(0);
            smartLockCard.setStatus(1);
            // 卡设置方式
            if (authType == 1) {// 永久
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, 365 * 1);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                try {
                    smartLockCard.setLimitDay(DateUtils.daysBetween(smartLockCard.getStartTime(), smartLockCard.getEndTime()));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            } else {// 时间期限
                smartLockCard.setStartTime(new Date());
                String addDaysTime = DateUtils.getAddDaysTime(new Date(), DateUtils.FORMAT_DATETIME_14, value);
                smartLockCard.setEndTime(DateUtils.convert(addDaysTime, DateUtils.FORMAT_DATETIME_14));
                smartLockCard.setLimitDay(value);
            }
            //授权CUP卡
            if (brandId == 4) {
                String resultStr = operationCardPassword(smartLockCard,byId.get().getSn());
                cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
                Integer code = (Integer) jsonObject.get("code");
                String msg = (String) jsonObject.get("msg");
                if (code != 0) {
                    return  Result.fail(msg);
                }
                //新增天网互联密码标识
                String identification = smartLockCard.getIdentification();
                if (StrUtil.isEmpty(identification)) {
                    identification = "L" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
                }
                smartLockCard.setIdentification(identification);
            }
            if (brandId == 5) {
                ResultBean<String> stringResultBean = smartLockHxkService.identityCardUnlocking(byId.get().getSn(), smartLockCard);
                if (!StatusCode.SUCCESS_CODE_10000.getErrorCode().equals(stringResultBean.getCode())) {
                    return Result.fail(stringResultBean.getMsg());
                }
                smartLockCard.setIdentification(smartLockCard.getCardNumber());
            }
            MCardWarehouse mCardWarehouse = byCardId.get(0);
            mCardWarehouse.setUseStatus((byte) 1);
            mCardWarehouseRepository.save(mCardWarehouse);
            smartLockCardRepository.save(smartLockCard);
            this.updateOauthNumber(brandId,lockId);
            return Result.success();
        } else {
            MCardWarehouse mCardWarehouse = byCardId.get(0);
            mCardWarehouse.setUseStatus((byte) 1);
            mCardWarehouseRepository.save(mCardWarehouse);
            // 接口调用
            log.info("lockAuthId={},lockId={},type={},cardNumber={},cardId={},authType={},value={}",lockAuthId,lockId,type,cardNumber,cardId,authType,value);
            String resultStr = httpGet( lockAuthId,  lockId,  type,cardNumber,  cardId,  authType,  value);
            Map mapObj = JSONObject.parseObject(resultStr,Map.class);
            String msg = (String) mapObj.get("msg");
            return  Result.fail(ResultCode.SUCCESS.getCode(),msg,null);
        }

    }

    /**
     * 授权CUP卡
     * @param smartLockCard
     * @param sn
     * @return
     */
    private String operationCardPassword(SmartLockCard smartLockCard, String sn) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = getToken();
        String startTime = DateUtil.formatDateTime(smartLockCard.getStartTime());
        String endTime = DateUtil.formatDateTime(smartLockCard.getEndTime());
        //四代授权CPU卡需要传8位16进制的数据；
        //String cardNum = String.format("%08X", Long.valueOf(smartLockCard.getCardId()));
        hashMap.put("deviceNum", sn);
        hashMap.put("identification", smartLockCard.getIdentification());
        hashMap.put("startTime", startTime);
        hashMap.put("endTime", endTime);
        hashMap.put("cardType", 0);
        hashMap.put("cardNum", smartLockCard.getCardId());
        String s = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/singleCard.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(GsonUtil.toJson(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return s;
    }

    /**
     * httpGet请求
     * @return
     */
    public String httpGet(  Long lockAuthId, Long lockId, Integer type,
                          String cardNumber, String cardId, Integer authType, Integer value) {
        try {
            if (value ==null){
                value=0;
            }
            String parameter="?lockAuthIds="+lockAuthId+"&types="+type+"&cardId="+cardId+"&values="+value+"&lockIds="+lockId+
                    "&cardNumber="+cardNumber+"&authTypes="+authType;
            HttpGet httpGet = new HttpGet(authCardsUrl+parameter);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            CloseableHttpClient createDefault = HttpClients.createDefault();
            CloseableHttpResponse result = createDefault.execute(httpGet);

            String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
            log.info("responseMsg=" + responseMsg);
            return responseMsg;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }



    /**
     * 后管调用 cpu卡库 冻结/解冻 tpGet请求
     * @param lockId 锁id
     * @param lockAuthId  授权id
     * @param type  类型：0:解冻 1:冻结
     * @param reason  冻结备注
     * @return
     */
    public String frozenOrUnfrozenChamadaUrlHttpGet(  Long lockId, Long lockAuthId, Integer type, String reason) {
        try {
            String parameter="?lockId="+lockId+"&lockAuthId="+lockAuthId+"&type="+type+"&reason="+reason;
            HttpGet httpGet = new HttpGet(frozenOrUnfrozenChamadaUrl+parameter);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            CloseableHttpClient createDefault = HttpClients.createDefault();
            CloseableHttpResponse result = createDefault.execute(httpGet);

            String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
            log.info("responseMsg=" + responseMsg);
            return responseMsg;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 后管调用 cpu卡库  单用户删除授权 tpGet请求
     * @param lockAuthId  授权id
     * @return
     */
    public String delCardAuthUrlHttpGet( Long lockAuthId) {
        try {
            String parameter="?lockAuthId="+lockAuthId;
            HttpGet httpGet = new HttpGet(delCardAuthUrl+parameter);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            CloseableHttpClient createDefault = HttpClients.createDefault();
            CloseableHttpResponse result = createDefault.execute(httpGet);

            String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
            log.info("responseMsg=" + responseMsg);
            return responseMsg;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public MCardWarehouse convert2(Row row, Sheet sheet, CellStyle style, Map<String, Integer> existMap, Workbook workbook,
                                   int rowNum, Map<String, MCardWarehouse> cardIdMap, Map<String, MCardWarehouse> cardNumberMap,Map<String, Integer> exist2Map) {
        MCardWarehouse cardWarehouse = new MCardWarehouse();

        //0.卡号
        Cell cardNumberCell = row.getCell(0);
        String cardNumber = getStr(cardNumberCell);
            if (StringUtils.isNotBlank(cardNumber)) {

            if (existMap.get(cardNumber) == null){
                existMap.put(cardNumber,rowNum);
                cardWarehouse.setCardNumber(cardNumber);
            }else {
                //验证Excel表数据是否重复
                Integer integer = existMap.get(cardNumber);
                Row rows = sheet.getRow(integer);
                Cell cells = rows.getCell(3);
                String temp1 = "";
                if (cells == null) {
                    cells = rows.createCell(3);
                } else {
                    if (cells.getCellTypeEnum() != CellType.BLANK) {
                        temp1 = getStr(cells) + ",";
                    }
                }
                cells.setCellStyle(style);
                cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(0)) + "Excel表数据已重复，数据已经存在");


                Cell cell = row.getCell(3);
                String temp2 = "";
                if (cell == null) {
                    cell = row.createCell(3);
                } else {
                    if (cell.getCellTypeEnum() != CellType.BLANK) {
                        temp2 = getStr(cell) + ",";
                    }
                }
                cell.setCellStyle(style);
                cell.setCellValue(temp2 + getStr(sheet.getRow(0).getCell(0)) + "Excel表数据已重复，数据已经存在");

                existMap.put(cardNumber,rowNum);
            }

            if (cardNumberMap.get(cardNumber) != null){
                Cell cells = row.getCell(3);
                String temp1 = "";
                if (cells == null) {
                    cells = row.createCell(3);
                } else {
                    if (cells.getCellTypeEnum() != CellType.BLANK) {
                        temp1 = getStr(cells) + ",";
                    }
                }
                cells.setCellStyle(style);
                cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(0)) + "数据库中已存在该数据！");
            }

            } else {
                Cell cells = row.getCell(3);
                String temp1 = "";
                if (cells == null) {
                    cells = row.createCell(3);
                } else {
                    if (cells.getCellTypeEnum() != CellType.BLANK) {
                        temp1 = getStr(cells) + ",";
                    }
                }
                cells.setCellStyle(style);
                cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(0)) + "不能为空");
            }


        //1. 卡ID
        Cell cardIdCell = row.getCell(1);
        String cardId = getStr(cardIdCell);
            if (StringUtils.isNotEmpty(cardId)) {

                if (exist2Map.get(cardId) == null){
                    existMap.put(cardId,rowNum);
                    cardWarehouse.setCardId(cardId);
                }else {
                    //验证Excel表数据是否重复
                    Integer integer = exist2Map.get(cardId);
                    Row rows = sheet.getRow(integer);
                    Cell cells = rows.getCell(3);
                    String temp1 = "";
                    if (cells == null) {
                        cells = rows.createCell(3);
                    } else {
                        if (cells.getCellTypeEnum() != CellType.BLANK) {
                            temp1 = getStr(cells) + ",";
                        }
                    }
                    cells.setCellStyle(style);
                    cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(1)) + "Excel表数据已重复，数据已经存在");


                    Cell cell = row.getCell(3);
                    String temp2 = "";
                    if (cell == null) {
                        cell = row.createCell(3);
                    } else {
                        if (cell.getCellTypeEnum() != CellType.BLANK) {
                            temp2 = getStr(cell) + ",";
                        }
                    }
                    cell.setCellStyle(style);
                    cell.setCellValue(temp2 + getStr(sheet.getRow(0).getCell(1)) + "Excel表数据已重复，数据已经存在");

                    existMap.put(cardId,rowNum);
                }


                if (cardIdMap.get(cardId) != null){
                    Cell cells = row.getCell(3);
                    String temp1 = "";
                    if (cells == null) {
                        cells = row.createCell(3);
                    } else {
                        if (cells.getCellTypeEnum() != CellType.BLANK) {
                            temp1 = getStr(cells) + ",";
                        }
                    }
                    cells.setCellStyle(style);
                    cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(1)) + "数据库中已存在该数据！");
                }



                if (cardId.equals(cardNumber)){
                    Cell cells = row.getCell(3);
                    String temp1 = "";
                    if (cells == null) {
                        cells = row.createCell(3);
                    } else {
                        if (cells.getCellTypeEnum() != CellType.BLANK) {
                            temp1 = getStr(cells) + ",";
                        }
                    }
                    cells.setCellStyle(style);
                    cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(1)) + "和卡ID不能一样！");
                }


            } else {
                Cell cells = row.getCell(3);
                String temp1 = "";
                if (cells == null) {
                    cells = row.createCell(3);
                } else {
                    if (cells.getCellTypeEnum() != CellType.BLANK) {
                        temp1 = getStr(cells) + ",";
                    }
                }
                cells.setCellStyle(style);
                cells.setCellValue(temp1 + getStr(sheet.getRow(0).getCell(1)) + "不能为空");
            }


        return cardWarehouse;
    }

    private String getStr(Cell cell) {


        if (cell == null || cell.getCellTypeEnum() == CellType.BLANK|| cell.getCellTypeEnum() == CellType._NONE) {
            if (cell != null) {
                log.warn("Cell is blank, row={}, column = {}", cell.getRowIndex(), cell.getColumnIndex());
            }
            return null;
        }

        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        }

        if (cell != null && cell.getCellTypeEnum() == CellType.NUMERIC) {
            DecimalFormat df = new DecimalFormat("0");
            return df.format(cell.getNumericCellValue());
        }

        if (cell != null && cell.getCellTypeEnum() == CellType.FORMULA) {
            if (cell.getCachedFormulaResultTypeEnum() == CellType.NUMERIC) {
                return String.valueOf(cell.getNumericCellValue());
            }
            if (cell.getCachedFormulaResultTypeEnum() == CellType.STRING) {
                return cell.getRichStringCellValue().toString();
            }
        }

        return null;
    }
    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    // 获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取PasS平台token
     *
     * @return
     */
    public String getToken() {
        String paaSToken = stringRedisTemplate.opsForValue().get("paaSToken");
        if (org.apache.commons.lang3.StringUtils.isEmpty(paaSToken)) {
            try {
                HttpPost httpPost = new HttpPost(tianWangHuLianCallbackUrl + "/api/login.do");
                CloseableHttpClient httpClient = HttpClients.createDefault();
                BasicResponseHandler handler = new BasicResponseHandler();
                Map<String, String> params = Maps.newHashMap();
                params.put("appKey", tianWangHuLianAppKey);
                params.put("secret", tianWangHuLianSecret);
                //设置请求格式
                StringEntity entity = new StringEntity(JSON.toJSONString(params), "utf-8");//解决中文乱码问题
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                //执行POST请求
                String execute = httpClient.execute(httpPost, handler);
                JSONObject resultJson = JSON.parseObject(execute);
                Object data = resultJson.get("data");
                JSONObject jsonObject = JSON.parseObject(data.toString());
                Object token = jsonObject.get("token");
                stringRedisTemplate.opsForValue().set("paaSToken", token.toString(), 30, TimeUnit.MINUTES); //30分钟
                return token.toString();
            } catch (Exception e) {
                return "获取失败";
            }
        }
        return paaSToken;
    }

    /**
     * 删除四代智能锁单个用户CUP卡
     * @param token
     * @param id 四代智能锁CUP卡id
     * @return
     */
    public Result deleteCpuCard(String token, Long id) {
        Optional<SmartLockCard> smartLockCard = smartLockCardRepository.findById(id);
        if (ObjectUtil.isNull(smartLockCard)) {
            return Result.fail("智能锁信息不存在");
        }
        Long lockId = smartLockCard.get().getLockId();
        Optional<SmartLock> smartLock = smartLockRepository.findById(lockId);
        String sn = smartLock.get().getSn();
        String identification = smartLockCard.get().getIdentification();
        //删除授权CUP卡
        String resultStr = deleteCard(identification,sn);
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
        Integer code = (Integer) jsonObject.get("code");
        String msg = (String) jsonObject.get("msg");
        if (code != 0) {
            return  Result.fail(msg);
        }
        smartLockCardRepository.deleteById(id);
        return Result.success(msg);
    }

    /**
     * 删除四代CPU卡接口
     * @param identification
     * @param sn
     * @return
     */
    private String deleteCard(String identification, String sn) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = getToken();
        hashMap.put("deviceNum", sn);
        hashMap.put("identification", identification);
        String s = HttpRequest.delete(tianWangHuLianCallbackUrl + "/api/singleCard.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(GsonUtil.toJson(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return s;
    }

    public void updateOauthNumber(Long brandId, Long lockId) {
        try {
            log.info("updateOauthNumber 更新智能锁授权人数, brandId={}, lockId={}", brandId, lockId);

            // if (brandId == 3L) {
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                log.info("updateOauthNumber 更新智能锁授权人数, 未找到锁 lockId={}", lockId);
                return;
            }
            SmartLock smartLock = lockOptional.get();
            Integer bindType = smartLock.getBindType();
            Integer bindStatus = smartLock.getBindStatus();

            int oauthNumber = 0;
            if (bindType == 1 && bindStatus == 1) {// 单位锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            } else if (bindType == 2 && bindStatus == 2) {// 个人锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 1);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            }

            smartLock.setOauthNumber(oauthNumber);
            smartLockRepository.save(smartLock);
            //}
        } catch (Exception e) {
            log.error("更新智能锁授权人数异常" + e.getMessage(), e);
        }
    }
}
